package zhongbo.java.air.flightpath.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import zhongbo.java.air.flightpath.mapper.FlightPathAddMapper;
import zhongbo.java.air.flightpath.model.FlightPathl;

@Slf4j
@Component
public class RedisSubscribeMyChaneIListener implements MessageListener {
    @Autowired
    private FlightPathAddMapper flightPathAddMapper;



    @Autowired
    private RedisPusChaneIPublisher publisher;
    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] messageBody=message.getBody();
        String msgString=new String(messageBody);
        log.info("接收到航迹的消息{}",msgString);

            try {
        JSONObject jsonObject = JSONUtil.parseObj(msgString);
        FlightPathl flightPath = new FlightPathl();

        flightPath.setIcaoCode(jsonObject.getStr("icaoCode"));
        flightPath.setTimestamp(jsonObject.getDate("timestamp"));
        flightPath.setLatitude(jsonObject.getDouble("latitude"));
        flightPath.setLongitude(jsonObject.getDouble("longitude"));
        flightPath.setAltitude(jsonObject.getDouble("altitude"));
        flightPath.setSpeed(jsonObject.getDouble("speed"));
        flightPath.setHeading(jsonObject.getDouble("heading"));
        flightPath.setSourceType(jsonObject.getStr("sourceType"));

        // 调用 add 方法保存数据
        add(flightPath);
    } catch (Exception e) {
        log.error("Error processing message: {}", msgString, e);
    }
}

    private FlightPathl add(FlightPathl flightPath) {
        String type = flightPath.getSourceType();
        if (StrUtil.isBlank(type)) {
            type = "";
        }
        flightPath.setSourceType(type); // 更新 sourceType 字段
        flightPathAddMapper.insert(flightPath);
        log.info("保存航迹数据: {}", flightPath);
        //发送到live_flight_path频道
        publisher.sendMessageJson(flightPath);
        return flightPath;
    }
}
